package demo;

import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

//Day07
public class Day17003 {
    public static void main(String[] args) {
        TreeSet<Book> set = new TreeSet<>();
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入书名和价格:");
//        输入五本书的名字与价格
        for(int i=0;i<5;i++){
            System.out.println("第"+(i+1)+"本书");
            set.add(new Book(scanner.next(),scanner.nextInt()));
        }

        System.out.println(set);
    }
}

class Book implements Comparable<Book>, Comparator<Book> {
    private String name;
    private Integer price;

    public Book() {
    }

    public Book(String name, Integer price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
//        compareTo的效果为：将类的属性进行比较，返回值小于0则放在tree左子树，反之放在tree右子树，从而排序
    @Override
    public int compareTo(Book book) {
        int result= this.getPrice()-book.getPrice();
        if(result==0)
            result=book.getName().compareTo(this.name);
        return result;
    }
//        效果同上
    @Override
    public int compare(Book book1, Book book2) {
        int result=book1.getPrice()-book2.getPrice();
        if(result==0)
            result= book1.getName().compareTo(book2.getName());
        return result;
    }
}
